$(function() {


    //自定义规则
    // $.validator.addMethod("规则名",函数) 返回true和fasle
    $.validator.addMethod("checkName", (value, element, param) => {
        // console.log(value, element, param);
        return /^[a-z]\w+/ig.test(value);
    })

    $("form").validate({
        //rules 规则
        rules: {
            name: {
                required: true, //用户名必填
                checkName: true, //开启自定义的骨子额
                rangelength: [6, 18], //长度6-18位
                remote: {
                    type: "get",
                    url: "/api/checkName"
                } //remote 远程,true和false
            },
            pwd: {
                required: true,
                rangelength: [6, 18]
            },
            pwd2: {
                equalTo: "#pwd"
            },
            nickname: {
                required: true,
            },
            phone: {
                rangelength: [11, 11],
                digits: true
            }
        },
        //messages 提示消息
        messages: {
            name: {
                required: "用户名必填哦~",
                checkName: "用户名不合法",
                rangelength: '用户名长度必须{0}-{1}',
                remote: "该用户名已注册!"
            },
            pwd: {
                required: "密码必填",
                rangelength: '长度必须{0}-{1}'
            },
            pwd2: {
                equalTo: "2次密码不一致"
            },
            nickname: {
                required: "昵称必填",
            },
            phone: {
                rangelength: "手机号必须11位",
                digits: "只能是数字"
            }
        },
        //等价于 onsubmit
        submitHandler() {
            //ajax...
            $('#reg').prop("disabled", true);

            var index = layer.load(1, {
                shade: [0.1, '#fff'] //0.1透明度的白色背景
            });

            $.ajax({
                url: "/api/reg",
                type: 'post',
                data: $("form").serialize(),
            }).then(function(res) {
                $('#reg').prop("disabled", false);
                layer.close(index);
                if (res && res.code == 200) {
                    layer.confirm("恭喜,注册成功!,是否立即去登录", {
                        btn: ["确定", "取消"]
                    }, function(tmpIndex) {
                        //由于点了确定.不会自动关闭确认框,需要
                        //手动关闭
                        layer.close(tmpIndex);
                        setTimeout(function() {
                            location.href = '../login.html';
                        }, 500);
                    }, function() {
                        //取消 会自动关闭窗口
                    });
                }
            })
            return false
        }
    })
})